package com.npf.imgserver.thread;

import com.npf.imgserver.utils.StringUtil;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;

import java.io.FileOutputStream;
import java.io.OutputStream;

/**
 * Created with IDEA
 * 异步线程 base64字符串 输出图片
 * author: NiPengFei
 * Date:18/9/23
 * Time:下午10:13
 */
@Data
public class GenerateImageThreadAsyc implements Runnable {

    public static final Logger logger = LoggerFactory.getLogger(GenerateImageThreadAsyc.class);

    /**
     * 图片base64格式
     */
    private String imgBase64;
    /**
     * 图片输出位置
     */
    private String imgFilePath;

    @Override
    public void run() {
        if (StringUtil.isNotBlank(this.imgBase64) && StringUtil.isNotBlank(this.imgBase64)) {
            //对字节数组字符串进行Base64解码并生成图片
            BASE64Decoder decoder = new BASE64Decoder();
            try {
                //Base64解码
                byte[] b = decoder.decodeBuffer(this.imgBase64);
                for (int i = 0; i < b.length; ++i) {
                    if (b[i] < 0) {
                        //调整异常数据
                        b[i] += 256;
                    }
                }
                //生成jpeg图片
                OutputStream out = new FileOutputStream(this.imgFilePath);
                out.write(b);
                out.flush();
                out.close();
            } catch (Exception e) {
                logger.error("base64字符串输出图片失败", e);
            }
        }

    }
}
